import os

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 检查文件是否存在
file_path = 'diabetes.csv'
if not os.path.exists(file_path):
    print("文件不存在")
    exit()

try:
    # 读取数据
    df = pd.read_csv(file_path)
    X = df.iloc[:, 1:3]
    y = df.iloc[:, -1]

    # 数据预处理：特征缩放
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)

    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)

    # 创建逻辑回归模型并训练
    model = LogisticRegression()
    model.fit(X_train, y_train)

    # 打印模型训练准确率
    train_accuracy = model.score(X_train, y_train)
    print(f"训练集准确率：{train_accuracy:.2f}")

    # 可视化决策边界
    x_min, x_max = X_scaled[:, 0].min() - 1, X_scaled[:, 0].max() + 1
    y_min, y_max = X_scaled[:, 1].min() - 1, X_scaled[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01))
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    # 绘制训练集和决策边界
    plt.figure(figsize=(8, 6))
    plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu, alpha=0.8)
    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=plt.cm.RdYlBu, edgecolors='k')
    plt.xlabel('Sepal Length (scaled)')
    plt.ylabel('Sepal Width (scaled)')
    plt.title('Logistic Regression - Diabetes Data')
    plt.show()

    # 在测试集上评估模型
    test_accuracy = model.score(X_test, y_test)
    print(f"测试集准确率：{test_accuracy:.2f}")

except Exception as e:
    print("发生异常:", e)
